package com.kingmed.kmss.framework.excel.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.kingmed.kmss.common.exception.BusinessException;
import com.kingmed.kmss.framework.excel.service.ExcelFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * Excel文件服务实现类
 */
@Service
@Slf4j
public class ExcelFileServiceImpl implements ExcelFileService {

    @Override
    public void excelFileDownload(HttpServletRequest request, HttpServletResponse response, Integer type, List<?> list, Class clazz, String templateFileName) throws IOException {
        try {
            // 为防止 文件名出现乱码
            final String userAgent = request.getHeader("USER-AGENT");
            String fileName = "";
            // IE浏览器
            if (StrUtil.contains(userAgent, "MSIE")) {
                fileName = URLEncoder.encode(templateFileName, "UTF-8");
            } else {
                // google、火狐浏览器
                if (StrUtil.contains(userAgent, "Mozilla")) {
                    fileName = new String(templateFileName.getBytes(), "ISO8859-1");
                } else {
                    // 其他浏览器
                    fileName = URLEncoder.encode(templateFileName, "UTF-8");
                }
            }
            // 设置让浏览器弹出下载提示框，而不是直接在浏览器中打开, type==0下载后浏览器直接查看
            response.setContentType("application/" + (type == 0 ? "octet-stream" : "x-download"));
            // 文件obs存储名称 毫秒时间戳 + "_" + 文件名称
            response.addHeader("Content-Disposition", (type == 0 ? "inline" : "attachment") + ";filename=" + fileName);
            BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            ExcelWriter excelWriter = EasyExcel.write(outputStream, clazz).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.write(list, writeSheet);
            excelWriter.finish();
        } catch (Exception e) {
            log.error("excel文件下载失败", e);
            throw new BusinessException("excel文件下载失败：" + e.getMessage());
        }
    }

}